package com.yxkj.syh.app.huarong.activities.creat;

import android.app.Application;
import android.view.View;

import androidx.annotation.NonNull;
import androidx.databinding.ObservableField;
import androidx.lifecycle.MutableLiveData;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.syh.app.basic.App;
import com.syh.app.basic.base.view_model.BaseViewModel;
import com.syh.app.basic.bindingAdp.view_click.ClickEvent;
import com.syh.app.basic.utils.ComUtil;
import com.syh.app.basic.utils.Tooast;
import com.syh.app.basic.utils.net.ApiObserver;
import com.trello.rxlifecycle2.android.ActivityEvent;
import com.yxkj.syh.app.huarong.adps.AddedGoodsAdp;
import com.yxkj.syh.app.huarong.bean.AliCityResponse;
import com.yxkj.syh.app.huarong.bean.AreaPlus;
import com.yxkj.syh.app.huarong.bean.CarInfo;
import com.yxkj.syh.app.huarong.bean.CreatOrderResponse;
import com.yxkj.syh.app.huarong.bean.OrderInfo;
import com.yxkj.syh.app.huarong.bean.ReturnCarAddressResponse;
import com.yxkj.syh.app.huarong.bean.ScanCarIdResponse;
import com.yxkj.syh.app.huarong.data_center.model.AliCityModel;
import com.yxkj.syh.app.huarong.data_center.model.CommonModel;
import com.yxkj.syh.app.huarong.data_center.model.OrderModel;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import chihane.jdaddressselector.AddressProvider;
import chihane.jdaddressselector.model.City;
import chihane.jdaddressselector.model.County;
import chihane.jdaddressselector.model.Province;
import chihane.jdaddressselector.model.Street;

/**
 * 创建者：SYH
 * 时间：2020/5/21 14:39
 * 编辑者：SYH、
 * 标签：
 * 补充说明：
 */
public class NewOrderVM extends BaseViewModel<ActivityEvent> {
    private AddedGoodsAdp mAddedGoodsAdp;
    private OrderInfo orderInfo = new OrderInfo();
    private CarInfo carHeadInfo;


    public NewOrderVM(@NonNull Application application) {
        super(application);
    }

    public ObservableField<Boolean> ofEmptyCar = new ObservableField<>(Boolean.TRUE);
    public ObservableField<String> ofFromArea = new ObservableField<>();
    public ObservableField<String> ofToArea = new ObservableField<>();
    public ObservableField<String> ofFromAddress = new ObservableField<>();
    public ObservableField<String> ofToAddress = new ObservableField<>();
    public ObservableField<String> ofCarHeadNo = new ObservableField<>();
    public ObservableField<String> ofCarTrailerNo = new ObservableField<>();

    public MutableLiveData<OrderInfo> mldCreatedEmptySuccess = new MutableLiveData<>();
    public MutableLiveData<OrderInfo> mldCreatedSuccess = new MutableLiveData<>();

    public ClickEvent nextClick = new ClickEvent() {
        @Override
        public void onClick(View view) {
            if (checkParameter()) {
                creatOrderInServer();
            }
        }
    };

    private boolean checkParameter() {
        if (ComUtil.hasEmpty(ofFromArea.get(), ofFromAddress.get(), ofToArea.get(), ofToAddress.get())) {
            Tooast.normalInfo("请完善地址信息");
            return false;
        } else if (ComUtil.hasEmpty(ofCarHeadNo.get())) {
            Tooast.normalInfo("请完善车辆信息");
            return false;
        } else if (!ofEmptyCar.get()) {
            if (mAddedGoodsAdp.getData().size() == 0) {
                Tooast.normalInfo("请填写货品信息");
                return false;
            }
        }
        return true;
    }

    private void creatOrderInServer() {
        orderInfo.setStartAddress(ofFromAddress.get());
        orderInfo.setEndAddress(ofToAddress.get());
        orderInfo.setCarId(carHeadInfo.getCode());
        orderInfo.setCarNo(carHeadInfo.getName());
        orderInfo.setSemitrailerNo(ofCarTrailerNo.get());
        orderInfo.setOrderProductList(mAddedGoodsAdp.getData());

        showLoading("creatOrder");
        if (ofEmptyCar.get()) {//创建空车货运单
            OrderModel.getOrderModel().creatEmptyCarOrder(orderInfo.getCreatRequest(), mLifecycleProvider.bindToLifecycle(), new ApiObserver<CreatOrderResponse>() {
                @Override
                public void onSuccess(CreatOrderResponse creatOrderResponse) {
                    hideLoading("creatOrder");
                    OrderInfo orderInfo1 = creatOrderResponse.getData();
                    mldCreatedEmptySuccess.setValue(orderInfo1);
                }

                @Override
                public void onFailed(int code, String msg) {
                    hideLoading("creatOrder");
                    Tooast.warning(msg);
                }
            });
        } else {
            OrderModel.getOrderModel().creatOrder(orderInfo.getCreatRequest(), mLifecycleProvider.bindToLifecycle(), new ApiObserver<CreatOrderResponse>() {
                @Override
                public void onSuccess(CreatOrderResponse creatOrderResponse) {
                    hideLoading("creatOrder");
                    OrderInfo orderInfo1 = creatOrderResponse.getData();
                    mldCreatedSuccess.setValue(orderInfo1);
                }

                @Override
                public void onFailed(int code, String msg) {
                    hideLoading("creatOrder");
                    Tooast.warning(msg);
                }
            });
        }
    }

    public void setAddedGoodsAdp(AddedGoodsAdp addedGoodsAdp) {
        this.mAddedGoodsAdp = addedGoodsAdp;
    }

    public void setCarHeadInfo(CarInfo carHeadInfo) {
        this.carHeadInfo = carHeadInfo;
        ofCarHeadNo.set(carHeadInfo.getName());
    }

    public OrderInfo getOrderInfo() {
        return orderInfo;
    }

    public void scanCarId(String path, int carType) {
        showLoading("scanCarId");
        String base64 = "data:image/jpg;base64," + ComUtil.imageToBase64(path);
        Map<String, Object> pMap = new HashMap<>();
        pMap.put("base64Image", base64);
        OrderModel.getOrderModel().scanCarId(pMap, mLifecycleProvider.bindToLifecycle(), new ApiObserver<ScanCarIdResponse>() {
            @Override
            public void onSuccess(ScanCarIdResponse scanCarIdResponse) {
                hideLoading("scanCarId");
                if (carType == 0) {
                    ofCarHeadNo.set(scanCarIdResponse.getData());
                } else {
                    ofCarTrailerNo.set(scanCarIdResponse.getData());
                }
            }

            @Override
            public void onFailed(int code, String msg) {
                hideLoading("scanCarId");
                Tooast.warning(msg);
            }
        });
    }

    public void returnCarGetAddress() {
        showLoading("returnCarGetAddress");
        CommonModel.getCommonModel().returnCarGetAddress(mLifecycleProvider.bindToLifecycle(), new ApiObserver<ReturnCarAddressResponse>() {
            @Override
            public void onSuccess(ReturnCarAddressResponse returnCarAddressResponse) {
                ReturnCarAddressResponse.Address address = returnCarAddressResponse.getData();
                NewOrderVM.this.orderInfo.setStartArea(address.getStartArea());
                NewOrderVM.this.orderInfo.setEndArea(address.getEndArea());
                NewOrderVM.this.orderInfo.setStartAreaIds(address.getStartAreaIds());
                NewOrderVM.this.orderInfo.setEndAreaIds(address.getEndAreaIds());
                ofFromArea.set(address.getStartArea().replace("/",""));
                ofFromAddress.set(address.getStartAddress());
                ofToArea.set(address.getEndArea().replace("/",""));
                ofToAddress.set(address.getEndAddress());
                hideLoading("returnCarGetAddress");
            }

            @Override
            public void onFailed(int code, String msg) {
                hideLoading("returnCarGetAddress");
                Tooast.normalInfo(msg);
            }
        });
    }


    /**
     * 地址选择器的数据源提供者
     */
    public AddressProvider addressProvider = new AddressProvider() {
        @Override
        public void provideProvinces(AddressReceiver<Province> addressReceiver) {
            addressReceiver.send(getProvince());
        }

        @Override
        public void provideCitiesWith(int provinceId, AddressReceiver<City> addressReceiver) {
            cities(provinceId, addressReceiver);
        }

        @Override
        public void provideCountiesWith(int cityId, AddressReceiver<County> addressReceiver) {
            counties(cityId, addressReceiver);
        }

        @Override
        public void provideStreetsWith(int countyId, AddressReceiver<Street> addressReceiver) {
            addressReceiver.send(null);
        }
    };

    /**
     * 查市
     */
    public void cities(int provinceId, AddressProvider.AddressReceiver<City> addressReceiver) {

        AliCityModel.getAliCityModel().getAliCity(getAreaPlusId(1, provinceId), mLifecycleProvider.bindToLifecycle(), new ApiObserver<AliCityResponse>() {
            @Override
            public void onSuccess(AliCityResponse response) {
                if (response.getShowapi_res_code() == 0) {
                    areaLevel2Pluses.clear();
                    areaLevel2Pluses.addAll(response.getShowapi_res_body().getData());
                    cities.clear();
                    for (int i = 0; i < areaLevel2Pluses.size(); i++) {
                        AreaPlus areaPlus = areaLevel2Pluses.get(i);
                        City city = new City();
                        city.id = i + 1;
                        city.name = areaPlus.getAreaName();
                        city.province_id = provinceId;
                        areaPlus.setCity(city);
                        cities.add(city);
                    }
                    addressReceiver.send(cities);
                }
            }

            @Override
            public void onFailed(int code, String msg) {
                Tooast.warning(msg);
            }
        });
    }

    /**
     * 查区县
     */
    public void counties(int cityId, AddressProvider.AddressReceiver<County> addressReceiver) {
        AliCityModel.getAliCityModel().getAliCity(getAreaPlusId(2, cityId), mLifecycleProvider.bindToLifecycle(), new ApiObserver<AliCityResponse>() {
            @Override
            public void onSuccess(AliCityResponse response) {
                if (response.getShowapi_res_code() == 0) {
                    areaLevel3Pluses.clear();
                    areaLevel3Pluses.addAll(response.getShowapi_res_body().getData());
                    counties.clear();
                    for (int i = 0; i < areaLevel3Pluses.size(); i++) {
                        AreaPlus areaPlus = areaLevel3Pluses.get(i);
                        County county = new County();
                        county.id = i + 1;
                        county.name = areaPlus.getAreaName();
                        county.city_id = cityId;
                        areaPlus.setCounty(county);
                        counties.add(county);
                    }
                    addressReceiver.send(counties);
                }
            }

            @Override
            public void onFailed(int code, String msg) {
                Tooast.warning(msg);
            }
        });
    }


    private List<AreaPlus> areaLevel1Pluses = new ArrayList<>();
    private List<AreaPlus> areaLevel2Pluses = new ArrayList<>();
    private List<AreaPlus> areaLevel3Pluses = new ArrayList<>();
    private List<Province> provinces = new ArrayList<>();
    private List<City> cities = new ArrayList<>();
    private List<County> counties = new ArrayList<>();

    /**
     * 读省
     *
     * @return
     */
    private List<Province> getProvince() {
        if (provinces.size() == 0) {
            try {
                // 获取json文件数据源,流的方式呈现
                InputStream inputStream = App.getApplication().getAssets().open("province.json");
                // 读取JSON文件流
                InputStreamReader inputStreamReader = new InputStreamReader(inputStream, "utf-8");
                BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
                String temp = "";
                String jsonSource = "";
                //一行一行的读取
                while ((temp = bufferedReader.readLine()) != null) {
                    jsonSource += temp;
                }
                //关闭
                bufferedReader.close();
                inputStream.close();

                JSONObject jsonObject = new JSONObject(jsonSource);
                List<AreaPlus> areaPluses = new Gson().fromJson(jsonObject.getString("data"), new TypeToken<List<AreaPlus>>() {
                }.getType());

                areaLevel1Pluses.clear();
                areaLevel1Pluses.addAll(areaPluses);

                for (int i = 0; i < areaLevel1Pluses.size(); i++) {
                    AreaPlus provincePlus = areaLevel1Pluses.get(i);
                    Province province = new Province();
                    province.name = provincePlus.getAreaName();
                    province.id = i + 1;
                    provinces.add(province);
                    provincePlus.setProvince(province);
                }
            } catch (IOException e) {
                e.printStackTrace();
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
        return provinces;
    }


    /**
     * 查 AreaPlusId
     *
     * @param subId 子类 id
     */
    public long getAreaPlusId(int level, int subId) {
        long id = 0l;

        if (level == 1) {
            for (AreaPlus areaPlus : areaLevel1Pluses) {
                if (areaPlus.getProvince().id == subId) {
                    id = Long.decode(areaPlus.getId());
                    break;
                }
            }
        } else if (level == 2) {
            for (AreaPlus areaPlus : areaLevel2Pluses) {
                if (areaPlus.getCity().id == subId) {
                    id = Long.decode(areaPlus.getId());
                    break;
                }
            }
        } else if (level == 3) {
            for (AreaPlus areaPlus : areaLevel3Pluses) {
                if (areaPlus.getCounty().id == subId) {
                    id = Long.decode(areaPlus.getId());
                    break;
                }
            }
        }


        return id;
    }
}
